package fengjzh.RenrenApp.tjjtds.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.xiaonei.api.XiaoneiException;
import com.xiaonei.api.XiaoneiRestClient;
import com.xiaonei.api.schema.Friend;
import com.xiaonei.api.schema.FriendsGetFriendsResponse;

import fengjzh.RenrenApp.tjjtds.common.Constants;

public class TestServlet extends HttpServlet {

	private static final long serialVersionUID = 4876997386995857797L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		out.println("<a href=\"/mytjjtds\">首页</a>&nbsp;&gt;&gt;&nbsp;结果页<br/><br/>");
		
		//printFriendList(request,out);
		
		queryPic(request,out);
		
		out.close();

	}
	
	private void queryPic(HttpServletRequest request, PrintWriter out){
		String queryStr = request.getParameter("queryStr");
		if(queryStr==null || "".equals(queryStr)){
			out.println("搜索词不能为空！");
			return;
		}
		try{
			StringBuffer urlbuf = new StringBuffer("http://124.192.33.194/newphoto/service/picquery?q=");
			urlbuf.append(URLEncoder.encode(queryStr, "UTF-8"));
			urlbuf.append("&t=1&psize=5&page=1");
			URL url = new URL(urlbuf.toString());
			InputStreamReader in = new InputStreamReader(url.openStream(), "UTF-8");
			
			SAXReader reader = new SAXReader();
			Document doc = reader.read(in);
			Element root = doc.getRootElement();
			Element pics = root.element("PicResources");
			Element pic;
			
			out.println("查询词："+queryStr+"<br/>");
			//out.println("结果数："+root.elementText("total")+"<br/>");
			out.println("<br/>");
			
			for (Iterator i = pics.elementIterator("PicResource"); i.hasNext();) {
				pic = (Element) i.next();
				//out.println("id:" + pic.elementText("id")+"<br/>");
				out.println("标题:" + pic.elementText("title")+"<br/>");
				out.println("<img src=\"" + pic.elementText("preurl1")+"\" alt=\""+pic.elementText("title")+"\" /><br/>");
				out.println("<br/>");
			}
			in.close();
		} catch(UnsupportedEncodingException e){
			dealException(e,out);
		} catch (MalformedURLException e) {
			dealException(e,out);
		} catch (IOException e) {
			dealException(e,out);
		} catch (DocumentException e) {
			dealException(e,out);
		}
	}

	private void printFriendList(HttpServletRequest request, PrintWriter out) {
		try {
			String sessKey = request.getParameter("xn_sig_session_key");

			if (sessKey == null || sessKey.equals("")) {
				for (Cookie i : request.getCookies()) {
					if (i.getName().equals(Constants.API_KEY + "_session_key")) {
						sessKey = i.getValue();
					}
				}
			}

			XiaoneiRestClient client = new XiaoneiRestClient(Constants.API_KEY,
					Constants.SECRET, sessKey);
			client.friends_getFriends();
			FriendsGetFriendsResponse resp = (FriendsGetFriendsResponse) client
					.getResponsePOJO();
			List<Friend> friends = resp.getFriend();

			for (Friend friend : friends) {
				out.println("<xn:name uid=\"" + friend.getId()
						+ "\" linked=\"true\" shownetwork=\"true\" />");
				out.println("<xn:profile-pic uid=\"" + friend.getId()
						+ "\" linked=\"true\" size=\"tiny\" />" + "<br/>");
			}
		} catch (XiaoneiException e) {
			dealException(e,out);
		} catch (IOException e) {
			dealException(e,out);
		} catch (Exception e) {
			dealException(e,out);
		}
	}
	
	private void dealException(Exception e, PrintWriter out){
		e.printStackTrace();
		out.println("Error Occurred!...<br/>");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

}
